package offer;

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

/**
 * 剑指 Offer 22. 链表中倒数第k个节点
 */
public class GetKthFromEnd {
    public ListNode getKthFromEnd(ListNode head, int k) {
        if (k <= 0) {
            return null;
        }
        int k1 = 0;
        boolean b = false;
        ListNode node1 = head;
        ListNode node2 = head;
        while (node1 != null) {
            node1 = node1.next;
            k1++;
            if (k1 == k) {
                b = true;
            }
            if (b) {
                node2 = node2.next;
            }
        }

        return node2;
    }
}
